package com.hzncc.flowable_diboot.service.impl;

import com.diboot.core.util.JSON;
import com.diboot.core.vo.JsonResult;
import com.diboot.core.vo.Pagination;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Objects;


/**
 * 天眼查接口
 *
 * @author 陈广煜
 * @date 2024/5/23
 */
@Service
@Slf4j
public class TianYanChaService {

    // 搜索接口 816
    @Value("${tian-yan-cha.url.search}")
    public String SEARCH_URL;
    // 详情接口 1116
    @Value("${tian-yan-cha.url.detail}")
    public String DETAIL_URL;
    @Value("${tian-yan-cha.url.detailSpecial}")
    public String DETAIL_SPECIAL_URL;
    // 接口token
    @Value("${tian-yan-cha.token}")
    public String TOKEN;

    /**
     * 企业查询
     *
     * @param name
     * @param pageSize 页大小
     * @param pageNum  页码
     * @return
     * @author 陈广煜
     * @date 2024/5/23
     */
    public JsonResult<?> search(String name, int pageSize, int pageNum) {
        String param = String.format("?word=%s&pageSize=%d&pageNum=%d", name, pageSize, pageNum);
        String url = SEARCH_URL + param;
        String resp = executeGet(url, TOKEN);
        if(resp == null) {
            return JsonResult.FAIL_EXCEPTION("接口异常，请稍候重试。");
        }
        // 数据处理
        Map<Object, Object> map = JSON.toMap(resp);
        if (!Objects.equals(map.get("error_code"), 0)) {
            return JsonResult.FAIL_EXCEPTION((String) map.get("reason"));
        }
        Map<String,Object> result = (Map<String, Object>) map.get("result");
        Integer total = (Integer) result.get("total");
        Object items = result.get("items");
        Pagination pagination = new Pagination();
        pagination.setTotalCount(total);
        pagination.setPageSize(pageSize);
        pagination.setPageIndex(pageNum);
        return JsonResult.OK(items).bindPagination(pagination);
    }

    /**
     * 获取企业详情
     *
     * @param name 企业全称
     * @return
     * @author 陈广煜
     * @date 2024/5/24
     */
    public JsonResult<?> detail(String name) {
        String param = String.format("?keyword=%s", name);
        String url = DETAIL_URL + param;
        String resp = executeGet(url, TOKEN);
        if(resp == null) {
            log.warn("接口异常，请稍候重试。");
            return specialDetail(param);
        }
        //  数据处理
        Map<Object, Object> map = JSON.toMap(resp);
        if (!Objects.equals(map.get("error_code"), 0)) {
            log.warn("接口异常，请稍候重试。");
            return specialDetail(param);
        }
        return JsonResult.OK(map.get("result"));
    }

    private JsonResult<?> specialDetail(String param) {
        String specialUrl = DETAIL_SPECIAL_URL + param;
        String specialResp = executeGet(specialUrl, TOKEN);

        if (specialResp == null) {
            return JsonResult.FAIL_EXCEPTION("备用接口异常，请稍候重试。");
        }

        Map<Object, Object> specialMap = JSON.toMap(specialResp);
        if (!Objects.equals(specialMap.get("error_code"), 0)) {
            return JsonResult.FAIL_EXCEPTION((String) specialMap.get("reason"));
        }

        return JsonResult.OK(specialMap.get("result"));
    }

    /**
     * http get请求
     *
     * @param url   接口url
     * @param token token
     * @return 返回接口数据
     */
    protected String executeGet(String url, String token) {
        BasicHttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, 1000);
        HttpConnectionParams.setSoTimeout(httpParams, 1000);
        HttpClient httpClient = new DefaultHttpClient(httpParams);
        String result = null;
        try {
            HttpGet get = new HttpGet(url);
            // 设置header
            get.setHeader("Authorization", token);
            // 设置类型
            HttpResponse response = httpClient.execute(get);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity, "utf-8");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            httpClient.getConnectionManager().shutdown();
        }
        return result;
    }

}
